package common;

import java.util.Hashtable;
import java.util.StringTokenizer;

import math.Relation;

import common.commands.CommandHelp;
import common.commands.ICommand;
import common.commands.ICommand.CommandValue;
import common.commands.CommandList;
import common.commands.LoadAltaRicaModel;
import common.commands.Print;
import common.commands.PrintModel;
import common.commands.Reach;

public class Commands {
	
	private static Hashtable<String, ICommand> commands = Prepare();
	
	public static Hashtable<String, ICommand> getCommands() {
		
		return commands;
	}
	
	private static Hashtable<String, ICommand> Prepare() {
		
		ICommand cmd;
		
		Hashtable<String, ICommand> tmp = new Hashtable<String, ICommand>();
		
		cmd = new Print();
		tmp.put(cmd.getName().toUpperCase(), cmd);
		
		cmd = new PrintModel();
		tmp.put(cmd.getName().toUpperCase(), cmd);
		
		cmd = new LoadAltaRicaModel();
		tmp.put(cmd.getName().toUpperCase(), cmd);
		
		cmd = new Reach();
		tmp.put(cmd.getName().toUpperCase(), cmd);
		
		cmd = new CommandHelp();
		tmp.put(cmd.getName().toUpperCase(), cmd);
		
		cmd = new CommandList();
		tmp.put(cmd.getName().toUpperCase(), cmd);
		
		return tmp;
	}
	
	
	public static CommandValue RunCommand(String input) {
		
		CommandValue ret;
		
		input = input.trim();
		
		StringTokenizer tok = new StringTokenizer(input);
		
		if (tok.hasMoreTokens()) {
			
			String cmd = tok.nextToken();
			String args = input.substring(cmd.length()).trim();
			
			ICommand command = commands.get(cmd.toUpperCase());
			
			if (command != null) {
				ret = command.run(args);
				
				if (ret != CommandValue.OK) {
					System.out.println("Error: the command " + cmd + " did not succeed");
				}
				
				return ret;
			}
			
			if (cmd.toUpperCase().equals("EXIT")) {
				return CommandValue.EXIT;
			} else {
				return Relation.parseRelation(input,new Relation());
			}
		}
		return CommandValue.UNKNOWN;
	}
}
